package com.weaver.seconddev.api.tl.price_approval_api;

/**
 * E9原始类路径:com.api.tl.price_approval_api.PAApprovedAction
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */

import java.util.ArrayList;
import java.util.List;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.api.tl.purchase_api.HrmResourceInfo;
import com.weaver.seconddev.api.tl.purchase_api.PlatformCommonService;
import com.weaver.seconddev.tl.util.DateUtils;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

import javax.annotation.Resource;

/**
 * PA流程正常审批完成触发接口动作：推送NPS版本审批结果
 *
 * @author th
 * @date 2023/10/9 16:01
 */
@org.springframework.stereotype.Service("tl_price_approval_api_PAApprovedAction")
public class PAApprovedAction implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    public static final org.slf4j.Logger logger_3ce9cde3 = LoggerFactory.getLogger(PAApprovedAction.class);
    @Resource(name = "tl_service_NPSCommonService2")
    private NPSCommonService npsCommonService;


    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        String pushApprovedResult = FAILURE_AND_CONTINUE;
        /* 获取requestId
 TODO 返回值:requestId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String requestId = requestInfo.getRequestid();
        try {
            /* 获取流程ID
 TODO 返回值:workflowId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
            String workflowId = requestInfo.getWorkflowid();
            // 最后操作者
            String lastOperator = requestInfo.getLastoperator();
            // 主表
            String mainTableName = requestInfo.getRequestManager().getBillTableName();
            logger_3ce9cde3.info(String.valueOf("RequestId:" + requestId + "======Into Approved Action======WorkflowId:" + workflowId + ",lastOperator:" + lastOperator + ",MainTableName:" + mainTableName));
            // 查询主表数据
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            //String queryMainTableSql = "select CSC_id,NPS_version from " + mainTableName + " where requestId = ?";
            String queryMainTableSql = "SELECT "+mainTableName+".csc_id AS CSC_id, "+mainTableName+".nps_version AS NPS_version\n" +
                    "FROM (\n" +
                    "\tSELECT b.*, a.requestid\n" +
                    "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+mainTableName+" b\n" +
                    "\tWHERE a.dataid = b.form_data_id\n" +
                    "\t\tAND a.delete_type = 0\n" +
                    "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                    ") "+mainTableName+"\n" +
                    "WHERE "+mainTableName+".requestid = ?\n" +
                    "\tAND "+mainTableName+".delete_type = 0\n" +
                    "\tAND "+mainTableName+".tenant_key = 'tl2k2r96ty'";
            logger_3ce9cde3.info(String.valueOf("Execute Sql:" + queryMainTableSql));
            String poolname = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            rs.executeQuery(queryMainTableSql, poolname, requestId);
            String csc = null;
            String versionId = null;
            if (rs.next()) {
                csc = rs.getString("CSC_id");
                versionId = rs.getString("NPS_version");
            }
            // 查询最后一名审批者(UPN)
            String lastOperatorUpn = null;
            List<HrmResourceInfo> hrmResourceInfoList = new ArrayList<>();
            HrmResourceInfo hrmResourceInfo = new HrmResourceInfo();
            hrmResourceInfo.setId(Long.parseLong(lastOperator));
            hrmResourceInfoList.add(hrmResourceInfo);
            List<HrmResourceInfo> resultList = PlatformCommonService.getUsersInfoBatch(hrmResourceInfoList);
            if (!resultList.isEmpty()) {
                lastOperatorUpn = resultList.get(0).getUpn();
            }
            // 拼接请求报文
            List<NPSVersionApprovalResult> npsVersionApprovalResultList = new ArrayList<>();
            NPSVersionApprovalResult npsVersionApprovalResult = new NPSVersionApprovalResult();
            npsVersionApprovalResult.setCsc(csc).setVersionId(versionId).setApprover(lastOperatorUpn).setStatus(NPSProcessApprovalStatusEnums.APPROVED.getCode()).setTime(DateUtils.getLocalDateTime()).setProcessType(NPSProcessTypeEnums.PA.getCode());
            npsVersionApprovalResultList.add(npsVersionApprovalResult);
            NPSRspMessage npsRspMessage = npsCommonService.updateApprovalResult(npsVersionApprovalResultList);
            if (npsRspMessage.getSuccess()) {
                pushApprovedResult = SUCCESS;
            }
        } catch (Exception e) {
            logger_3ce9cde3.error(e.getMessage());
        }
        logger_3ce9cde3.info(String.valueOf("RequestId:" + requestId + "======Out Approved Action======ReturnResult:" + pushApprovedResult));
        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", pushApprovedResult, requestInfo.getRequestManager()));
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
